<!--
 * @description  : 证件-许可文书送达回证
 * @descriptionDetail: 证件-许可文书送达回证
 * @copyright    : 浙江烟草
 * @author       : sy
 * @create       : 2022-08-18 15:29:13
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999">
    </theme-navbar>
    <!-- #endif -->
    <view class="main-content">
      <u-form :rules="rules" :model="certificatesData" :error-type="errorType" ref="uForm">
        <u-form-item :required="true" label="受送达人" label-width="labelWidth" prop="receivePerson">
          <u-input
            placeholder="请输入"
            :disabled="isDisabled"
            input-align="right"
            v-model="certificatesData.receivePerson"
          />
        </u-form-item>
        <u-form-item label="联系电话" label-width="labelWidth" prop="receiveContactTel">
          <u-input
            placeholder="请输入"
            :disabled="isDisabled"
            input-align="right"
            v-model="certificatesData.receiveContactTel"
          />
        </u-form-item>
        <u-form-item label="送达人" :required="true" right-icon="arrow-right" label-width="labelWidth" prop="toReceivePerson" ref="toReceivePersonRef">
          <u-input
            input-align="right"
            :auto-height="true"
            placeholder="请选择"
            :disabled="isDisabled"
            v-model="certificatesData.toReceivePerson"
            @click="receivePersonHandle"
          />
        </u-form-item>
        <u-form-item label="送达地点" :label-position="labelPosition" :required="true" label-width="labelWidth" prop="serviceAddr">
          <u-input placeholder="请输入" :disabled="isDisabled" v-model="certificatesData.serviceAddr" />
        </u-form-item>
        <u-form-item
          label="送达日期"
          :required="true"
          :label-width="labelWidth"
          prop="serviceDate"
          right-icon="arrow-right"
          ref="changeRefS"
        >
          <u-input
            placeholder="请选择"
            input-align="right"
            :disabled="true"
            :clearable="false"
            v-model="certificatesData.serviceDate"
            @click="isShow('isShowTime')"
          />
        </u-form-item>
        <u-form-item
          label="文书送达方式"
          label-width="labelWidth"
          right-icon="arrow-right"
          :required="true"
          prop="sendTypeName"
          ref="sendTypeNameRef"
        >
          <u-input
            placeholder="请选择"
            input-align="right"
            :disabled="true"
            v-model="certificatesData.sendTypeName"
            @click="isShow('showSendType')"
          />
          <u-select :list="sendTypeList" v-model="showSendType" @confirm="sendTypeConfirm"></u-select>
        </u-form-item>
        <u-form-item
          :label="sendTypeLabel"
          label-width="labelWidth"
          prop="serviceStyleAdded"
          v-show="certificatesData.docSendType&&certificatesData.docSendType!='L2902'"
        >
          <u-input placeholder="请输入" v-model="certificatesData.serviceStyleAdded" />
        </u-form-item>
        <u-form-item label="送达文书" label-width="labelWidth" :required="true" right-icon="arrow-right" prop="docName" ref="docNameRef">
          <u-input
            input-align="right"
            :auto-height="true"
            placeholder="请选择"
            :disabled="true"
            v-model="certificatesData.docName"
            @click="sendDocHandle"
          />
        </u-form-item>
        <u-form-item label="文书编号" label-width="labelWidth">
          <u-input
            input-align="right"
            :auto-height="true"
            placeholder="请输入"
            :disabled="true"
            v-model="certificatesData.docNo"
          />
        </u-form-item>
        <u-form-item label="签收人(签名或印章)" label-width="labelWidth" prop="receiverName">
          <u-input
            placeholder="请输入"
            :disabled="isDisabled"
            input-align="right"
            v-model="certificatesData.receiverName"
          />
        </u-form-item>
        <u-form-item
          label=""
          :label-width="labelWidth"
          prop="receiverDate"
          right-icon="arrow-right"
        >
          <u-input
            placeholder="请选择签字日期"
            :disabled="true"
            :clearable="false"
            input-align="right"
            v-model="certificatesData.receiverDate"
            @click="isShow('isShowReceiverTime')"
          />
        </u-form-item>
        <u-form-item label="证明人(签名或印章)" label-width="labelWidth" prop="witnessName">
          <u-input
            placeholder="请输入"
            :disabled="isDisabled"
            input-align="right"
            v-model="certificatesData.witnessName"
          />
        </u-form-item>
        <u-form-item
          label=""
          :label-width="labelWidth"
          prop="witnessDate"
          right-icon="arrow-right"
        >
          <u-input
            placeholder="请选择签字日期"
            :disabled="true"
            :clearable="false"
            input-align="right"
            v-model="certificatesData.witnessDate"
            @click="isShow('isShowWitnessTime')"
          />
        </u-form-item>
        <u-form-item label="备注" :label-position="labelPosition" label-width="labelWidth" prop="remark">
          <u-input
            type="textarea"
            :disabled="isDisabled"
            placeholder="请输入"
            v-model="certificatesData.remark"
          />
        </u-form-item>
      </u-form>
    </view>
    <view class="query-btn">
      <u-button
        type="primary"
        class="u-btn u-m-r-25"
        v-if="!docIns.step || docIns.step == 'edit'"
        @click="submitBtn('save')"
      >
        保存
      </u-button>
      <u-button
        type="primary"
        class="u-btn"
        v-if="!docIns.step || docIns.step == 'edit'"
        @click="submitBtn('submit')"
      >
        提交
      </u-button>
      <u-button
        type="primary"
        class="u-btn u-m-l-25"
        v-if="!!docIns.step && docIns.step != 'edit'"
        @click="downloadFile"
      >
        打印
      </u-button>
    </view>
    <u-calendar mode="date" max-date="2099-12-31" v-model="isShowTime" @change="changeDate('serviceDate',$event)">
    </u-calendar>
    <u-calendar
      mode="date"
      max-date="2099-12-31"
      v-model="isShowReceiverTime"
      @change="changeDate('receiverDate',$event)"
    ></u-calendar>
    <u-calendar
      mode="date"
      max-date="2099-12-31"
      v-model="isShowWitnessTime"
      @change="changeDate('witnessDate',$event)"
    ></u-calendar>
  </view>
</template>

<script>
import certificateService from "@/service/certificate/certificate.service.js";
import commonService from "@/service/common/common.service";
import {LOG_STATUS,LOG_OP_TYPE,} from '@/service/common/mapping/enum.js';
export default {
  components: {},
  data() {
    return {
      showSendType: false,
      certificatesData: {
        docName:'',
      },
      sendDocData: {},
      docIns: {},
      beginTime:"",
      preParams: {}, // 上个页面传过来的案件信息
      errorType: ['border-bottom','message',],
      labelPosition: "top",
      labelWidth: '280',
      isDisabled: false,
      isAction:false,// 送达人校验
      isDocName:false,// 送达文书校验
      rules: {
        toReceivePerson:[{
          validator:(rule, value, callback) => {
            return this.$u.test.empty(value) ? false : true;
          },
          message: '请选择送达人',
          trigger:['blur','change',],
        },],
        docName:[{
          validator:(rule, value, callback) => {
            return !this.$u.test.empty(value);
          },
          message: '请选择送达文书',
          trigger:['blur','change',],
        },],
        serviceDate:[{
          required: true,
          message: '请选择送达日期',
          trigger:['blur','change',],
        },],
        sendTypeName:[{
          required: true,
          message: '请选择送达方式',
          trigger:['blur','change',],
        },],
      },
      isShowTime: false,
      isShowReceiverTime: false,
      isShowWitnessTime: false,
      doc: {},
      sendTypeLabel: '',
      // sendTypeName: '',
      sendTypeList: [{
        value: 'L2902',
        label: '直接送达',
      },
      {
        value: 'L2901',
        label: '邮寄送达',
      },
      {
        value: 'L2903',
        label: '留置送达',
      },
      {
        value: 'L2904',
        label: '其他',
      },
      ],
    }
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  onLoad() {
    this.preParams = this.getRouteParam();
    commonService.getCurrentTime().then(res2 => {
      this.beginTime = res2.success ? res2.msg : this.$u.timeFormat(Date.now(), 'yyyy-mm-dd hh:MM:ss');
    });
  },
  watch: {
    isShowTime() {
      this.$refs.changeRefS.validation();
    },
    isAction(){
      this.$refs.toReceivePersonRef.validation();  
    },
    isDocName(){
      this.$refs.docNameRef.validation();
    },
    showSendType(){
      this.$refs.sendTypeNameRef.validation();
    },
  },
  created() {
    this.initDocData();
  },
  methods: {
    initDocData() {
      let params = {
        id: this.preParams.docInsUuid,
        docUuid: this.preParams.docUuid,
        bizUuid: this.preParams.bizUuid,
      }
      certificateService.getServiceDoc(params).then((res) => {
        if (res.data.length == 1) {
          let docData = res.data[0];
          this.init(docData);
          this.certificatesData = docData;
        } else {
          let docData = Object.assign(res.data[0], res.data[1]);
          this.init(docData);
          this.certificatesData = docData;
        }
      })
      certificateService.getDocIns(this.preParams.docInsUuid).then((dr) => {
        this.docIns = dr.bean;
        this.isDisabled = this.docIns.step != 'edit';
      })
    },
    // 格式化数据
    init(docData) {
      if (docData.serviceContent) {
        let jsonA = JSON.parse(docData.serviceContent);
        this.sendDocData.docNo = jsonA[0].docNo;
        this.sendDocData.docName = jsonA[0].docName;
      }

      if (docData.docSendType) {
        this.sendTypeList.forEach(item => {
          if (item.value == docData.docSendType) {
            this.certificatesData.sendTypeName = item.label;
          }
        })
        if (docData.docSendType != 'L2902') {
          if (docData.docSendType == 'L2901') {
            this.sendTypeLabel = '邮寄回执单编号:';
          } else if (docData.docSendType == 'L2903') {
            this.sendTypeLabel = '事由:';
          } else {
            this.sendTypeLabel = '';
          }
        }
      }
    },
    // 送达方式确认按钮
    sendTypeConfirm(e) {
      this.certificatesData.sendTypeName = e[0].label;
      this.certificatesData.docSendType = e[0].value;
      if (e[0].value == 'L2901') {
        this.sendTypeLabel = '邮寄回执单编号:';
      } else if (e[0].value == 'L2903') {
        this.sendTypeLabel = '事由:';
      } else {
        this.sendTypeLabel = '';
      }
    },
    // 文书下载
    downloadFile(fileId, titleName, isDownload) {
      if (!this.docIns.pdfFileId) {
        this.$u.toast("没有文书");
        return;
      }
      this.setRouteParam({
        fileId: this.docIns.pdfFileId,
      });
      this.$u.route('pages/commonPage/printerComponent');
    },
    // 控制弹窗显示的方法
    isShow(type) {
      if (this.isDisabled) return;
      this[type] = true;
    },
    // 送达人选择点击事件
    receivePersonHandle() {
      if (this.isDisabled) return;
      this.$u.route({
        url: "pages/certificate/components/licReceivePerson",
        params: {
          isSingle: true,
        },
        type: "to",
      });
      this.isAction = true;
    },
    // 送达文书点击事件
    sendDocHandle() {
      if (this.isDisabled) return;
      this.$u.route({
        url: "pages/certificate/components/sendDoc",
        params: {
          isSingle: true,
          bizUuid: this.preParams.bizUuid,
        },
        type: "to",
      });
      this.isDocName = true;
    },
    // 页面返回数据
    updateBackState(param) {
      // 送达人数据
      if (param.backPersonUuid) {
        this.$set(this.certificatesData, 'toReceivePerson', param.backPersonUuid[0].personName + ' (执法证号' +
                        param.backPersonUuid[0].leCertNo + ')');
        this.$set(this.certificatesData, 'toReceivePersonUuid', param.backPersonUuid[0].personUuid);
        this.isAction = false;
      }
      // 送达文书数据
      if (param.backSendDoc) {
        this.$set(this.certificatesData, 'docNo', param.backSendDoc[0].docCodeTitle);
        this.$set(this.certificatesData, 'docName', param.backSendDoc[0].docName);
        this.$set(this.certificatesData, 'docUuid', param.backSendDoc[0].docUuid);
        this.isDocName = false;
      }
    },
    changeDate(type, e) {
      let month = '';
      let day = '';
      month = e.month < 10 ? '0' + e.month : e.month;
      day = e.day < 10 ? '0' + e.day : e.day;
      this.certificatesData[type] = e.year + '年' + month + '月' + day + '日';
    },
    // 表单验证
    validForm() {
      let basicValid = false;
      this.$refs.uForm.validate(valid => {
        if (valid) {
          basicValid = true;
          console.log('表单验证通过');
        } else {
          basicValid = false;
          console.log('表单验证失败');
        }
      });
      return basicValid;
    },
    // 保存/提交
    submitBtn(type) {
      if (!this.validForm()) return;
      let serviceContent = [];
      this.sendDocData.docName = this.certificatesData.docName;
      this.sendDocData.docNo = this.certificatesData.docNo;
      this.sendDocData.docUuid = this.certificatesData.docUuid;
      serviceContent.push(this.sendDocData);
      this.certificatesData.serviceContent = JSON.stringify(serviceContent);
      certificateService.saveServiceDoc(this.certificatesData, this.preParams.docUuid, this.preParams
        .docInsUuid, this.preParams.titemUuid, 'edit').then((dr) => {
        if (dr.success) {
          if (type === 'submit') {
            this.doSubmit();
          } else {
            this.saveBehaviorLog(0, this.docIns);
            this.$u.toast("保存成功");
          }
        } else {
          this.$u.toast(dr.msg);
        }
      })
    },
    // 提交
    doSubmit() {
      certificateService.submitServiceDoc(this.certificatesData, this.preParams.docUuid, this.preParams
        .docInsUuid, this.preParams.titemUuid, 'edit').then((res) => {
        if (res.success == true) {
          this.$u.toast("提交成功");
          certificateService.getDocIns(this.docIns.docInsUuid).then((doc) => {
            this.docIns = doc.bean;
            this.saveBehaviorLog(1, this.docIns);
            this.isDisabled = this.docIns.step != 'edit';
          });
          this.backPrev({
            paramKey: "athService",
            // param: this.preParams,
          });
        } else {
          this.$u.toast(res.msg);
        }
      })
    },
    /**
	 * @param {Boolean} status 提交还是保存
	 */
    saveBehaviorLog(status, doc){
      commonService.getCurrentTime().then(res2 => {
        let param = {
          bizUuid: doc.bizUuid,
          docUuid:doc.docUuid,
          docInsUuid: doc.docInsUuid, 
          bizType:LOG_STATUS.B007,
          operationType: status == 0 ? LOG_OP_TYPE.saveDoc : LOG_OP_TYPE.submitDoc,
          beginTime: this.beginTime,
          endTime: res2.success ? res2.msg : this.$u.timeFormat(Date.now(), 'yyyy-mm-dd hh:MM:ss'),
          remark: doc.configIns.docName,
        };
        this.beginTime = param.endTime;
        commonService.saveBehaviorLog(param).then(res => {
          console.log(res);
        }).catch(e => {
          console.log(e);
        });
      });
    },
  },
}
</script>

<style lang="scss" scoped>
    @import "../certificate_common.scss";
</style>
